<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="这一节来讲解 h 函数的使用">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue3学习笔记（3）：h和createVNode函数">
<meta property="og:url" content="https://wyatex.online/Vue3/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9Ah%E5%87%BD%E6%95%B0/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="这一节来讲解 h 函数的使用">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-10-14T14:52:23.000Z">
<meta property="article:modified_time" content="2023-05-05T01:25:47.081Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="前端">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="Vue3">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://wyatex.online/Vue3/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9Ah%E5%87%BD%E6%95%B0/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/Vue3/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9Ah%E5%87%BD%E6%95%B0/","path":"Vue3/Vue3学习笔记（3）：h函数/","title":"Vue3学习笔记（3）：h和createVNode函数"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Vue3学习笔记（3）：h和createVNode函数 | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%85%88%E8%A1%A5%E5%85%85%E4%B8%80%E7%82%B9%E7%BB%84%E4%BB%B6%E7%9B%B8%E5%85%B3%E7%9A%84%E7%9F%A5%E8%AF%86"><span class="nav-number">1.</span> <span class="nav-text">先补充一点组件相关的知识</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#h-%E5%87%BD%E6%95%B0%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-number">2.</span> <span class="nav-text">h 函数的使用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8E%BB%E7%9C%8B%E4%B8%80%E4%B8%8B-h-%E5%87%BD%E6%95%B0%E7%9A%84%E6%BA%90%E7%A0%81"><span class="nav-number">3.</span> <span class="nav-text">去看一下 h 函数的源码</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#createVNode"><span class="nav-number">4.</span> <span class="nav-text">createVNode</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%BA%90%E7%A0%81%E6%9F%A5%E7%9C%8B"><span class="nav-number">4.1.</span> <span class="nav-text">源码查看</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        <div class="sidebar-inner sidebar-post-related">
          <div class="animated">
              <div class="links-of-blogroll-title"><i class="fa fa-signs-post fa-fw"></i>
    相关文章
  </div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/Vue3/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%882%EF%BC%89%EF%BC%9AProps/" rel="bookmark">
        <time class="popular-posts-time">2021-10-14</time>
        <br>
      Vue3学习笔记（2）：Props
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/Vue3/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%885%EF%BC%89%EF%BC%9Ajsx/" rel="bookmark">
        <time class="popular-posts-time">2021-10-17</time>
        <br>
      Vue3学习笔记（5）：jsx
      </a>
    </li>
  </ul>

          </div>
        </div>
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/Vue3/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9Ah%E5%87%BD%E6%95%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Vue3学习笔记（3）：h和createVNode函数 | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Vue3学习笔记（3）：h和createVNode函数
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-10-14 22:52:23" itemprop="dateCreated datePublished" datetime="2021-10-14T22:52:23+08:00">2021-10-14</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-05-05 09:25:47" itemprop="dateModified" datetime="2023-05-05T09:25:47+08:00">2023-05-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Vue3/" itemprop="url" rel="index"><span itemprop="name">Vue3</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>这一节来讲解 h 函数的使用</p>
<span id="more"></span>

<h1 id="先补充一点组件相关的知识"><a href="#先补充一点组件相关的知识" class="headerlink" title="先补充一点组件相关的知识"></a>先补充一点组件相关的知识</h1><p>首先<code>.vue</code>不是前端可以使用的一种格式，需要打包工具将这些文件编译打包成 js 文件。<br>而且比如像：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;div&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">alt</span>=<span class="string">&quot;Vue logo&quot;</span> <span class="attr">src</span>=<span class="string">&quot;./assets/logo.png&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">HelloWorld</span> <span class="attr">msg</span>=<span class="string">&quot;Welcome to Your Vue.js + TypeScript App&quot;</span> /&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>这段代码，最后也不会是一个 html 格式的代码，而是一种以 h 函数描述的代码。</p>
<h1 id="h-函数的使用"><a href="#h-函数的使用" class="headerlink" title="h 函数的使用"></a>h 函数的使用</h1><p>首先 h 函数是用来定义 DOM 节点的函数。上面的 html 标签可以表示成这样：</p>
<figure class="highlight js"><figcaption><span>main.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; createApp, h, defineComponent &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"><span class="comment">// import App from &#x27;./App.vue&#x27;</span></span><br><span class="line"><span class="keyword">import</span> <span class="title class_">HelloWorld</span> <span class="keyword">from</span> <span class="string">&#x27;./components/HelloWorld.vue&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">App</span> = <span class="title function_">defineComponent</span>(&#123;</span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="title function_">h</span>(<span class="string">&#x27;div&#x27;</span>, &#123; <span class="attr">id</span>: <span class="string">&#x27;app&#x27;</span> &#125;, [</span><br><span class="line">      <span class="title function_">h</span>(<span class="string">&#x27;img&#x27;</span>, &#123; <span class="attr">alt</span>: <span class="string">&#x27;Vue logo&#x27;</span>, <span class="attr">src</span>: <span class="string">&#x27;./assets/logo.png&#x27;</span> &#125;),</span><br><span class="line">      <span class="title function_">h</span>(<span class="title class_">HelloWorld</span>, &#123; <span class="attr">msg</span>: <span class="string">&#x27;Welcome to Your Vue.js + TypeScript App&#x27;</span> &#125;),</span><br><span class="line">    ])</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="title function_">createApp</span>(<span class="title class_">App</span>).<span class="title function_">mount</span>(<span class="string">&#x27;#app&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>可以看到页面成功渲染出来，但是图片并没有正常显示。这是因为写<code>.vue</code>文件时，写在 template 里的 src 会通过打包工具（比如 vue-loader）去找到正确的目录。可以改成这样：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> img = <span class="built_in">require</span>(<span class="string">&#x27;./assets/logo.png&#x27;</span>) <span class="comment">// eslint-disable-line</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">App</span> = <span class="title function_">defineComponent</span>(&#123;</span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="title function_">h</span>(<span class="string">&#x27;div&#x27;</span>, &#123; <span class="attr">id</span>: <span class="string">&#x27;app&#x27;</span> &#125;, [</span><br><span class="line">      <span class="title function_">h</span>(<span class="string">&#x27;img&#x27;</span>, &#123; <span class="attr">alt</span>: <span class="string">&#x27;Vue logo&#x27;</span>, <span class="attr">src</span>: img &#125;),</span><br><span class="line">      <span class="title function_">h</span>(<span class="title class_">HelloWorld</span>, &#123; <span class="attr">msg</span>: <span class="string">&#x27;Welcome to Your Vue.js + TypeScript App&#x27;</span> &#125;),</span><br><span class="line">    ])</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>就能看到图片正常显示了，加<code>// eslint-disable-line</code>的原因是 eslint 默认禁止使用 required，这里为了演示先关掉这一行的 eslint 检查。<br>至于样式问题，可以写一个 css 文件并引入即可，因为上面的写法是为了让你更好的了解 vue 的 sfc 也就是 vue 文件是如何编译打包的。<br>如果以后写 vue 文件时，看到某个 dom 结构你能快速的想出他是如果跟 h 函数这种结构对应的，那将对对你排查问题又非常大的好处。</p>
<h1 id="去看一下-h-函数的源码"><a href="#去看一下-h-函数的源码" class="headerlink" title="去看一下 h 函数的源码"></a>去看一下 h 函数的源码</h1><p>我们直接去 vue-next 源码看 h 函数的实现（implementation）：</p>
<figure class="highlight ts"><figcaption><span>package/runtime-core/src/h.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Actual implementation</span></span><br><span class="line"><span class="comment">// 可以看到h函数先接收一个type，第二个参数是props或者children，第三个是children。</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">h</span>(<span class="params"><span class="keyword">type</span>: <span class="built_in">any</span>, propsOrChildren?: <span class="built_in">any</span>, children?: <span class="built_in">any</span></span>): <span class="title class_">VNode</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> l = <span class="variable language_">arguments</span>.<span class="property">length</span></span><br><span class="line">  <span class="keyword">if</span> (l === <span class="number">2</span>) &#123;</span><br><span class="line">    <span class="comment">// 当长度为2的时候，说明第二个是参数或者是children</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="title function_">isObject</span>(propsOrChildren) &amp;&amp; !<span class="title function_">isArray</span>(propsOrChildren)) &#123;</span><br><span class="line">      <span class="comment">// single vnode without props</span></span><br><span class="line">      <span class="keyword">if</span> (<span class="title function_">isVNode</span>(propsOrChildren)) &#123;</span><br><span class="line">        <span class="comment">// 传入的是VNode，说明是children</span></span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">createVNode</span>(<span class="keyword">type</span>, <span class="literal">null</span>, [propsOrChildren])</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 不是children，那就是props</span></span><br><span class="line">      <span class="comment">// props without children</span></span><br><span class="line">      <span class="keyword">return</span> <span class="title function_">createVNode</span>(<span class="keyword">type</span>, propsOrChildren)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 是数组，说明是children</span></span><br><span class="line">      <span class="comment">// omit props</span></span><br><span class="line">      <span class="keyword">return</span> <span class="title function_">createVNode</span>(<span class="keyword">type</span>, <span class="literal">null</span>, propsOrChildren)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (l &gt; <span class="number">3</span>) &#123;</span><br><span class="line">      <span class="comment">// 长度大于3的话，取出props之后的children参数</span></span><br><span class="line">      children = <span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">slice</span>.<span class="title function_">call</span>(<span class="variable language_">arguments</span>, <span class="number">2</span>)</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (l === <span class="number">3</span> &amp;&amp; <span class="title function_">isVNode</span>(children)) &#123;</span><br><span class="line">      children = [children]</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="title function_">createVNode</span>(<span class="keyword">type</span>, propsOrChildren, children)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到 h 函数实际上就是用来返回一个 VNode 的工具，就是通过各种规则的判断，将你写的不那么规范的代码变得更加规范一点。</p>
<h1 id="createVNode"><a href="#createVNode" class="headerlink" title="createVNode"></a>createVNode</h1><p>上面的代码我们可以直接改成<code>createVNode</code>的形式去写 dom 结构:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">App</span> = <span class="title function_">defineComponent</span>(&#123;</span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="title function_">createVNode</span>(<span class="string">&#x27;div&#x27;</span>, &#123; <span class="attr">id</span>: <span class="string">&#x27;app&#x27;</span> &#125;, [</span><br><span class="line">      <span class="title function_">createVNode</span>(<span class="string">&#x27;img&#x27;</span>, &#123; <span class="attr">alt</span>: <span class="string">&#x27;Vue logo&#x27;</span>, <span class="attr">src</span>: img &#125;),</span><br><span class="line">      <span class="title function_">createVNode</span>(<span class="title class_">HelloWorld</span>, &#123;</span><br><span class="line">        <span class="attr">msg</span>: <span class="string">&#x27;Welcome to Your Vue.js + TypeScript App&#x27;</span>,</span><br><span class="line">      &#125;),</span><br><span class="line">    ])</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>这样就更符合 template 解析后的结构了。</p>
<h2 id="源码查看"><a href="#源码查看" class="headerlink" title="源码查看"></a>源码查看</h2><p>直接去看 vnode 相关的源码：</p>
<figure class="highlight ts"><figcaption><span>package/runtime-core/src/vnode.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> createVNode = (</span><br><span class="line">  __DEV__ ? createVNodeWithArgsTransform : _createVNode</span><br><span class="line">) <span class="keyword">as</span> <span class="keyword">typeof</span> _createVNode</span><br><span class="line"></span><br><span class="line"><span class="comment">// 可以看到createVNode是_createVNode的一个别名</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">_createVNode</span>(<span class="params"></span></span><br><span class="line"><span class="params">  <span class="keyword">type</span>: VNodeTypes | ClassComponent | <span class="keyword">typeof</span> NULL_DYNAMIC_COMPONENT,</span></span><br><span class="line"><span class="params">  props: (Data &amp; VNodeProps) | <span class="literal">null</span> = <span class="literal">null</span>,</span></span><br><span class="line"><span class="params">  children: <span class="built_in">unknown</span> = <span class="literal">null</span>,</span></span><br><span class="line"><span class="params">  patchFlag: <span class="built_in">number</span> = <span class="number">0</span>,</span></span><br><span class="line"><span class="params">  dynamicProps: <span class="built_in">string</span>[] | <span class="literal">null</span> = <span class="literal">null</span>,</span></span><br><span class="line"><span class="params">  isBlockNode = <span class="literal">false</span></span></span><br><span class="line"><span class="params">  <span class="comment">// patchFlag、dynamicProps、isBlockNode是优化相关的参数</span></span></span><br><span class="line"><span class="params">  <span class="comment">// 在使用.vue文件时，打包工具将会为我们加上这些内容</span></span></span><br><span class="line"><span class="params"></span>): <span class="title class_">VNode</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (!<span class="keyword">type</span> || <span class="keyword">type</span> === <span class="variable constant_">NULL_DYNAMIC_COMPONENT</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (__DEV__ &amp;&amp; !<span class="keyword">type</span>) &#123;</span><br><span class="line">      <span class="title function_">warn</span>(<span class="string">`Invalid vnode type when creating vnode: <span class="subst">$&#123;<span class="keyword">type</span>&#125;</span>.`</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">type</span> = <span class="title class_">Comment</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// ....</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="title function_">createBaseVNode</span>(</span><br><span class="line">    <span class="keyword">type</span>,</span><br><span class="line">    props,</span><br><span class="line">    children,</span><br><span class="line">    patchFlag,</span><br><span class="line">    dynamicProps,</span><br><span class="line">    shapeFlag,</span><br><span class="line">    isBlockNode,</span><br><span class="line">    <span class="literal">true</span></span><br><span class="line">  )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在最后的最后，虽然可以直接用 createVNode，但是官方既然提供了 h 函数，那么这个函数肯定是对我们有很多好处的，所以尽量还是用 h 函数而不是 createVNode 函数。</p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/Vue3/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9Ah%E5%87%BD%E6%95%B0/" title="Vue3学习笔记（3）：h和createVNode函数">https://wyatex.online/Vue3/Vue3学习笔记（3）：h函数/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
              <a href="/tags/%E5%89%8D%E7%AB%AF/" rel="tag"># 前端</a>
              <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
              <a href="/tags/Vue3/" rel="tag"># Vue3</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/Vue3/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%882%EF%BC%89%EF%BC%9AProps/" rel="prev" title="Vue3学习笔记（2）：Props">
                  <i class="fa fa-angle-left"></i> Vue3学习笔记（2）：Props
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/Vue3/Vue3%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%884%EF%BC%89%EF%BC%9Asetup/" rel="next" title="Vue3学习笔记（4）：setup函数">
                  Vue3学习笔记（4）：setup函数 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
